CS50 Lesson 2

CS50
code
lesson
Author

Ryan curtis

Published

January 20, 2023

I thought it would be fun to track all of my progress learning python, even the VERY humble beginnings. Any of the posts with the CS50 tag are simply copy/pastes of my code from lessons, along with a copy/paste of what the assignment actually wanted me to do for context.

Meal Time

Suppose that you’re in a country where it’s customary to eat breakfast between 7:00 and 8:00, lunch between 12:00 and 13:00, and dinner between 18:00 and 19:00. Wouldn’t it be nice if you had a program that could tell you what to eat when?

In meal.py, implement a program that prompts the user for a time and outputs whether it’s breakfast time, lunch time, or dinner time. If it’s not time for a meal, don’t output anything at all. Assume that the user’s input will be formatted in 24-hour time as #:## or ##:##. And assume that each meal’s time range is inclusive. For instance, whether it’s 7:00, 7:01, 7:59, or 8:00, or anytime in between, it’s time for breakfast.

Structure your program per the below, wherein convert is a function (that can be called by main) that converts time, a str in 24-hour format, to the corresponding number of hours as a float. For instance, given a time like "7:30" (i.e., 7 hours and 30 minutes), convert should return 7.5 (i.e., 7.5 hours).

```{{python}}
def main():
    #Get user input
    user_input = input("What time is it? ").lower().strip()

    #Decide which convert function to use & assign to variable
    if user_input.endswith("a.m.") or user_input.endswith("p.m."):
        time = ampm_convert(user_input)
    else:
        time = convert(user_input)

    #If tree to decide if it is breakfast, lunch or dinner time
    if 7 <= time <= 8:
        print("Breakfast time!"n)
    elif 12 <= time <= 13:
        print("Lunch time!")
    elif 18 <= time <= 19:
        print("Dinner time!")


def convert(time):
    #Split time into hour & minutes
    hour, minute = time.split(":")
    #Return time as a float value
    return(float(int(minute) / 60) + float(hour))

def ampm_convert(time):
    #determine whether time is a.m. or p.m.
    if time.endswith("a.m."):
        #Remove suffix
        time = time.removesuffix("a.m.")
        #Split time into hour & minutes
        hour, minute = time.split(":")
        #Return time as a float value
        return(float(int(minute) / 60) + float(hour))
    elif time.endswith("p.m."):
        #Remove suffix
        time = time.removesuffix("p.m.")
        #Split time into hour & minutes
        hour, minute = time.split(":")
        #Return time as a float value + 12 hours since it is p.m. time
        return(float(int(minute) / 60) + float(hour) + 12)
    else:
        return("error")



main()
```

Math Interpreter

Python already supports math, whereby you can write code to add, subtract, multiply, or divide values and even variables. But let’s write a program that enables users to do math, even without knowing Python.

In a file called interpreter.py, implement a program that prompts the user for an arithmetic expression and then calculates and outputs the result as a floating-point value formatted to one decimal place. Assume that the user’s input will be formatted as x y z, with one space between x and y and one space between y and z, wherein:

  • x is an integer

  • y is +, -, *, or /

  • z is an integer

For instance, if the user inputs 1 + 1, your program should output 2.0. Assume that, if y is /, then z will not be 0.

Note that, just as python itself is an interpreter for Python, so will your interpreter.py be an interpreter for math!

```{{python}}
def main():
    #get expression
    expression = input("Expression: ")

    #Split expression into x/y/z
    x, y, z = expression.split(" ", 2)

    #Determine arithmetic sign for y, and perform expression
    if y == "+":
        result = float(int(x) + int(z))
        print(round(result, 1))
    elif y == "-":
        result = float(int(x) - int(z))
        print(round(result, 1))
    elif y == "*":
        result = float(int(x) * int(z))
        print(round(result, 1))
    else:
        result = float(int(x) / int(z))
        print(round(result, 1))


main()
```

File Extensions

Even though Windows and macOS sometimes hide them, most files have file extensions, a suffix that starts with a period (.) at the end of their name. For instance, file names for GIFs end with .gif, and file names for JPEGs end with .jpg or .jpeg. When you double-click on a file to open it, your computer uses its file extension to determine which program to launch.

Web browsers, by contrast, rely on media types, formerly known as MIME types, to determine how to display files that live on the web. When you download a file from a web server, that server sends an HTTP header, along with the file itself, indicating the file's media type. For instance, the media type for a GIF is image/gif, and the media type for a JPEG is image/jpeg. To determine the media type for a file, a web server typically looks at the file's extension, mapping one to the other.

See developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types for common types.

In a file called extensions.py, implement a program that prompts the user for the name of a file and then outputs that file's media type if the file's name ends, case-insensitively, in any of these suffixes:

  • .gif

  • .jpg

  • .jpeg

  • .png

  • .pdf

  • .txt

  • .zip

If the file's name ends with some other suffix or has no suffix at all, output application/octet-stream instead, which is a common default.

```{{python}}
def main():
    #Get user input & strip & convert to lowercase
    user_input = input("Please enter your file name & extension: ").lower().strip()


    #Construct if tree to print corresponding MIME type, determine by file suffix
    if user_input.endswith(".gif"):
        print("image/gif")
    elif user_input.endswith(".jpg") or user_input.endswith(".jpeg"):
        print("image/jpeg")
    elif user_input.endswith(".png"):
        print("image/png")
    elif user_input.endswith(".pdf"):
        print("application/pdf")
    elif user_input.endswith(".txt"):
        print("text/plain")
    elif user_input.endswith(".zip"):
        print("application/zip")
    else:
        print("application/octet-stream")


main()
```

Home Federal Savings Bank

In season 7, episode 24 of Seinfeld, Kramer visits a bank that promises to give $100 to anyone who isn't greeted with a "hello." Kramer is instead greeted with a "hey," which he insists isn't a "hello," and so he asks for $100. The bank's manager proposes a compromise: "You got a greeting that starts with an 'h,' how does $20 sound?" Kramer accepts.

In a file called bank.py, implement a program that prompts the user for a greeting. If the greeting starts with "hello", output $0. If the greeting starts with an "h" (but not "hello"), output $20. Otherwise, output $100. Ignore any leading whitespace in the user's greeting, and treat the user's greeting case-insensitively.

``` {{python}}
def main():
    #Get user input & strip & convert to lowercase
    user_input = input("How would you like to greet the patron? ").strip().lower()

    #If they say hello, give $0
    if user_input == "hello":
        print("$0")

    #if string is not just "hello", split string up to isolate greeting word, then match each case to their respective payouts
    else:
        greet_word, dump1 = user_input.split(" ", 1)
        match greet_word:
            case "hello,":
                print("$0")
            case "how":
                print("$20")
            case _:
                print("$100")


main()
```

Deep Thought

"All right," said the computer, and settled into silence again. The two men fidgeted. The tension was unbearable.
"You're really not going to like it," observed Deep Thought.
"Tell us!"
"All right," said Deep Thought. "The Answer to the Great Question…"
"Yes…!"
"Of Life, the Universe and Everything…" said Deep Thought.
"Yes…!"
"Is…" said Deep Thought, and paused.
"Yes…!"
"Is…"
"Yes…!!!…?"
"Forty-two," said Deep Thought, with infinite majesty and calm."

The Hitchhiker's Guide to the Galaxy, Douglas Adams

In deep.py, implement a program that prompts the user for the answer to the Great Question of Life, the Universe and Everything, outputting Yes if the user inputs 42 or (case-insensitively) forty-two or forty two. Otherwise output No.

```{{python}}
def main():
    #Ask user for input & turn all characters to lowercase so the program is not case sensitive & Strip spaces away
    user_input = input("What is the answer to the Great Question of Life, the Universe and Everything? ").lower().strip()

    match user_input:
        case "42" | "forty-two" | "forty two":
            print("Yes")
        case _:
            print("No")


main()
```